package be.rivendale.renderer.mk2;

import be.rivendale.renderer.mk2.data.Frame;
import be.rivendale.renderer.mk2.data.Rectangle;
import be.rivendale.renderer.mk2.data.Segment;
import be.rivendale.renderer.mk2.window.WindowConsumer;

import javax.swing.*;
import java.util.List;

public class Commander implements Consumer {
    private LoadBalancer loadBalancer;
    private WindowConsumer windowConsumer;
    private List<Rectangle> rectangles;
    private int countArrived;
    double startTime;

    public Commander(LoadBalancer loadBalancer, WindowConsumer windowConsumer) {
        this.loadBalancer = loadBalancer;
        this.windowConsumer = windowConsumer;
        rectangles = new Frame().createSegments();
        countArrived = 0;
    }

    @Override
    public void onConsumerStarted() {
        JOptionPane.showMessageDialog(null, "Click OK to start rendering pipeline.");
        startTime = System.nanoTime();
        loadBalancer.dispatch(rectangles);
    }

    @Override
    public void onSegmentComplete(Segment segment) {
        countArrived++;
        if (countArrived == rectangles.size()) {
            double stopTime = System.nanoTime();
            System.out.format("DONE in %.2fms\n", (stopTime - startTime) / (1000 * 1000));
            countArrived = 0;
            startTime = System.nanoTime();
            allDone();
        }
    }

    private void allDone() {
        for (Rectangle rectangle : rectangles) {
            Segment segment = new Segment(rectangle);
            windowConsumer.onSegmentComplete(segment);
        }
        loadBalancer.dispatch(rectangles);
    }
}
